;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Corruption.WjServicePartForecast", [])
        .controller("WjServicePartForecastCtrl", ["$scope", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService","$stateParams", function ($scope, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService,$stateParams) {
            $scope.handleMultiInput = function (e) {
                $scope.condition.materialsNos = UserContextService.MultiInput(e.target.value);
            };

            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.toolbarConfig = {
                showColConfig: false
            };


            $scope.condition = {};
            $scope.dataList = [];
            $scope.tableConfig = {
                fixedWidth: 100,
                scrollWidth: 1400,
                tableCol: [
                    {
                        name: "代理商",
                        dataField: "serviceName",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "保养件类型",
                        dataField: "typeDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "产品型号",
                        dataField: "proModelDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "一级分类",
                        dataField: "materialsType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "二级分类",
                        dataField: "materialsSecType",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "实际库存数量",
                        dataField: "realAmount",
                        width: 160,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "应采购数量",
                        dataField: "purchaseQty",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购数量差异值",
                        dataField: "purchaseQtySub",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "实际库存金额",
                        dataField: "realMoney",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "应采购金额",
                        dataField: "purchaseMoney",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "采购金额差异值",
                        dataField: "purchaseMoneySub",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "预警时间",
                        dataField: "inAlarmTime",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "解除预警时间",
                        dataField: "outAlarmTime",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "预警时长（天）",
                        dataField: "alarmDays",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "备注",
                        dataField: "remark",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "单据状态",
                        dataField: "statusShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "已生成督办单",
                        dataField: "dbdFlagShow",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: 'operate',
                        name: "操作",
                        width: 60,
                        isShow: true,
                        isFixed: true,
                    },
                ]
            };
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: { left: $scope.tableConfig.fixedWidth + "px" }
                };
            };

            $scope.exportParam = {
                sectionParam: { ids: [] },
                allUrl: ybHttp.RequestUrl("device", "/wjServicePartForecast/exportAll")
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function getDataList(curPage) {
                $scope.markInfo.allChecked = false;
                $scope.markInfo.curRow = -1;
                $scope.exportParam.sectionParam.ids = [];

                var service = "device";
                var reqUrl = "/wjServicePartForecast/list";

                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }

                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: angular.copy($scope.condition)
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.inAlarmTime = $filter("YbDate")(item.inAlarmTime, 'yyyy-MM-dd');
                        item.outAlarmTime = $filter("YbDate")(item.outAlarmTime, 'yyyy-MM-dd');
                        item.statusShow = $filter("ProgressStatus")(item.status, 'priceChangeInstru');
                        item.dbdFlagShow = $filter("ProgressStatus")(item.dbdFlag, 'deleteState');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }


            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectAll = function (list, type) {
                for (var i = 0, len = list.length; i < len; i++) {
                    list[i].isChecked = angular.isUndefined(type) ? $scope.markInfo.allChecked : $scope.markInfo["allChecked" + type];
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    if (!checkAll(list)) {
                        selectAll = false;
                    } else {
                        selectAll = true;
                    }
                }
                if (angular.isDefined(type)) {
                    $scope.markInfo["allChecked" + type] = selectAll;
                } else {
                    $scope.markInfo.allChecked = selectAll;
                }
                getBillIds();
            };
            //手动同步销售单据
            $scope.handleSync = function () {
                ybWidget.ShowMessage("同步报表数据？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/wjServicePartForecast/doTask";

                    ybHttp.Get(service, reqUrl).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.addWarning = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要生成督办单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/wjServicePartForecast/addDbd";

                    ybHttp.Post(service, reqUrl, selectedDatas.map(s => s.id)).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            function handleUpdateRemark(ids) {
                ybWidget.ShowConfirm("维护备注", [{ label: '备注' }]).then(function (data) {
                    var service = "device";
                    var reqUrl = "/wjServicePartForecast/update";

                    var param = {
                        id: ids.join(","),
                        remark: data[0].value,
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            }

            $scope.updateRemarkBatch = function () {
                const selectedDatas = $scope.dataList.filter(df => df.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }
                handleUpdateRemark(selectedDatas.map(s => s.id));
            };


            $scope.updateRemark = function (item) {
                handleUpdateRemark([item.id]);
            };

            $scope.activeFlag = [true, false, false, false];
			// 切换标签页
			$scope.changeTab = function (index) {
				$scope.activeFlag = [false, false, false, false];
				$scope.activeFlag[index] = true;

				$scope.submitted = false;
			};

			$scope.echartsOption1 = {
				title: {
					text: '保养件容量预测-代理商'
				},
				legend: {
					data: ['库存金额', '应采购金额']
				},
				label: {
					show: true,
					position: 'top',
				},
				xAxis: [
					{
						type: 'category',
						axisLabel: {
							rotate: 45
						},
						data: []
					}
				],
				series: [{ name: '库存金额', type: 'bar' }, { name: '应采购金额', type: 'bar' }],
				dataZoom: [
					{
						type: 'inside',
					}
				]
			};

			$scope.echartsCondition1 = {};
			$scope.echartsSearch1 = function (valid) {
				if (!valid) {
					$scope.submitted = true;
					return;
				}

				ybHttp.Post('device', '/wjServicePartForecast/queryWjServicePartForecast1Rpt', $scope.echartsCondition1).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					const resT = resp.value || [];
					$scope.echartsOption1.xAxis[0].data = resT.map(r => r.purchaseOrgName);
					$scope.echartsOption1.series[0].data = resT.map(r => r.realMoney);
					$scope.echartsOption1.series[1].data = resT.map(r => r.purchaseMoney);
				});
			};

            $scope.echartsOption2 = {
				title: {
					text: '保养件容量预测-二级分类'
				},
				legend: {
					data: ['库存金额', '应采购金额']
				},
				label: {
					show: true,
					position: 'top',
				},
				xAxis: [
					{
						type: 'category',
						data: []
					}
				],
				series: [{ name: '库存金额', type: 'bar' }, { name: '应采购金额', type: 'bar' }],
				dataZoom: [
					{
						type: 'inside',
					}
				]
			};

			$scope.echartsCondition2 = {};
			$scope.echartsSearch2 = function (valid) {
				if (!valid) {
					$scope.submitted = true;
					return;
				}

				ybHttp.Post('device', '/wjServicePartForecast/queryWjServicePartForecast2Rpt', $scope.echartsCondition2).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					const resT = resp.value || [];
					$scope.echartsOption2.xAxis[0].data = resT.map(r => r.materialsSecType);
					$scope.echartsOption2.series[0].data = resT.map(r => r.realMoney);
					$scope.echartsOption2.series[1].data = resT.map(r => r.purchaseMoney);
				});
			};

            // 选择代理商
			$scope.selectDealer = function (obj) {
				var param = {
					name: "代理商",
					type: "dealer",
					isPlatCompany: 1
				};
				ybWidget.SingleSelector(param).then(function (data) {
					obj.purchaseOrgNameLike = data.companyName;
				})
			};
            //保养件容量预测预警-编辑
            var btnPermissionCode = {
                wjServicePartForecastEdit: window.ActionCode.wjServicePartForecastEdit,
                wjServicePartForecastExport: window.ActionCode.wjServicePartForecastExport,
                wjServicePartForecastToDbd:window.ActionCode.wjServicePartForecastToDbd,
            };
            $scope.btnPermission = {
                wjServicePartForecastEdit: true,
                wjServicePartForecastExport: true,
                wjServicePartForecastToDbd: true,
            };
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            (function () {
                $scope.setFixedWidth();
                if ($stateParams.billNo) {
					$scope.condition.id = $stateParams.billNo
					getDataList();
				}else {
					getDataList();
				}
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
        ;
})(window, window.angular);
